package com.rabbit.controller;

import com.github.pagehelper.PageInfo;
import com.rabbit.annotation.Log;
import com.rabbit.annotation.LoginUser;
import com.rabbit.constant.OperType;
import com.rabbit.db.entity.User;
import com.rabbit.exception.BusinessException;
import com.rabbit.service.ConfigService;
import com.rabbit.util.ResultGenUtil;
import com.rabbit.validate.base.Delete;
import com.rabbit.validate.base.Insert;
import com.rabbit.validate.base.Update;
import com.rabbit.vo.ResultVO;
import com.rabbit.vo.req.ConfigReq;
import com.rabbit.vo.res.ConfigRes;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <h1>参数管理</h1>
 *
 * @author zjw
 * @date 2022/1/21 14:44
 */
@RestController
@RequestMapping("/config")
public class ConfigController {

    @Resource
    private ConfigService configService;

    /**
     * 参数列表
     */
    @PostMapping("/list")
    public ResultVO<Object> list(@RequestBody ConfigReq configReq) {
        PageInfo<ConfigRes> pageInfo = configService.queryConfigList(configReq);
        return ResultGenUtil.genSuccess(pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 删除参数
     */
    @PostMapping("/delete")
    @Log(name = "参数管理", type = OperType.DELETE)
    public ResultVO<Object> deleteConfig(@Validated(Delete.class) @RequestBody ConfigReq configReq) {
        configService.deleteConfig(configReq);
        return ResultGenUtil.genSuccess();
    }

    /**
     * 查询指定参数
     */
    @GetMapping("/queryConfigById")
    public ResultVO<Object> queryConfigById(@RequestParam Long configId) {
        return ResultGenUtil.genSuccess(configService.queryConfigById(configId));
    }

    /**
     * 新增用户
     */
    @PostMapping("/add")
    @Log(name = "参数管理", type = OperType.INSERT)
    public ResultVO<Object> addConfig(@LoginUser User loginUser, @Validated(Insert.class) @RequestBody ConfigReq configReq) throws BusinessException {
        configService.checkUnique(configReq, 1);
        configReq.setOperatorUserName(loginUser.getUserName());
        configService.addConfig(configReq);
        return ResultGenUtil.genSuccess();
    }

    /**
     * 修改用户
     */
    @PostMapping("/update")
    @Log(name = "参数管理", type = OperType.UPDATE)
    public ResultVO<Object> updateRole(@LoginUser User loginUser, @Validated(Update.class) @RequestBody ConfigReq configReq) throws BusinessException {
        configService.checkUnique(configReq, 2);
        configReq.setOperatorUserName(loginUser.getUserName());
        configService.updateConfig(configReq);
        return ResultGenUtil.genSuccess();
    }
}
